from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from PIL import Image
import io

# Configure Chrome options
chrome_options = Options()
chrome_options.add_argument("--headless")  # Run in headless mode
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--window-size=1920,1080")

# Initialize the WebDriver
service = Service('C:\javasoft\chromedriver-win64\chromedriver.exe')  # Replace with your chromedriver path
driver = webdriver.Chrome(service=service, options=chrome_options)

# Open the webpage
driver.get('file:///C:/projects/python/test/test.html')  # Replace with your URL

# 获取网页的高度
total_height = driver.execute_script("return document.body.scrollHeight")
 
# 获取浏览器视口的高度
viewport_height = driver.execute_script("return window.innerHeight")
 
# 计算需要截取的段数（每段高度为视口高度）
num_screenshots = total_height // viewport_height + (1 if total_height % viewport_height != 0 else 0)
 
# 初始化一个空的列表来存储每个段落的截图（作为字节流）
screenshots = []
 
# 滚动并截取每个段落的截图
for i in range(num_screenshots):
    # 滚动到指定位置
    driver.execute_script(f"window.scrollTo(0, {i * viewport_height});")
    
    # 等待页面加载（如果需要）
    # 例如：time.sleep(2)  # 注意：这里不推荐使用time.sleep，因为它不是基于条件的等待
    # 更好的做法是使用WebDriverWait等待某些元素加载完成
    
    # 截取当前视口的截图
    screenshot = driver.get_screenshot_as_png()
    screenshots.append(screenshot)
 
# 创建一个新的Image对象来拼接所有的截图
# 注意：这里假设网页的宽度没有超过视口的宽度，如果超过了，需要额外处理
total_width = driver.execute_script("return document.body.clientWidth")
stitched_image = Image.new('RGB', (total_width, total_height))
 
# 将每个截图粘贴到stitched_image的相应位置
y_offset = 0
for screenshot in screenshots:
    img = Image.open(io.BytesIO(screenshot))
    stitched_image.paste(img, (0, y_offset))
    y_offset += viewport_height
 
# 保存拼接后的截图
stitched_image.save('hello.png')


# Wait for the element to be visible
element = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.ID, 'hello'))  # Replace with your element locator
)

left = element.location['x']
top = element.location['y']
right = element.location['x'] + element.size['width']
bottom = element.location['y'] + element.size['height']
print(left, top, right, bottom)

im = Image.open('hello.png') 
im = im.crop((left, top, right, bottom))
im.save('hello.png')

# Close the WebDriver
driver.quit()